﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MstscHelperApp
{
    public partial class Form2 : Form
    {
        string mstscjsonPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "mstscdata.json");
        public Form2()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            List<MsctcInfo> mstscInfos = new List<MsctcInfo>();
            #region 验证输入
            if (string.IsNullOrEmpty(textBox1.Text))
            {
                MessageBox.Show("请输入分组");
                return;
            }
            if (string.IsNullOrEmpty(textBox2.Text))
            {
                MessageBox.Show("请输入远程主机地址");
                return;
            }
            if (string.IsNullOrEmpty(textBox3.Text))
            {
                MessageBox.Show("请输入登录账号");
                return;
            }
            if (string.IsNullOrEmpty(textBox4.Text))
            {
                MessageBox.Show("请输入登录密码");
                return;
            }
            #endregion
            #region 获取本地数据
            if (File.Exists(mstscjsonPath))
            {
                //如果存在
                string jsonData = File.ReadAllText(mstscjsonPath);
                if (!string.IsNullOrEmpty(jsonData))
                {
                    mstscInfos = JsonHelper.JsonToT<List<MsctcInfo>>(jsonData);
                }
            }
            #endregion
            #region 保存数据
            if (mstscInfos.Exists(m => m.IP == textBox2.Text))
            {
                MessageBox.Show($"地址：[{textBox2.Text}]已存在。");
                return;
            }
            mstscInfos.Add(new MsctcInfo
            {
                Group = textBox1.Text,
                IP = textBox2.Text,
                Desc = textBox5.Text,
                UserName = textBox3.Text,
                Password = textBox4.Text
            });
            string json = JsonHelper.TtoJson(mstscInfos);
            if (File.Exists(mstscjsonPath))
            {
                File.Delete(mstscjsonPath);
            }
            File.WriteAllText(mstscjsonPath, json, Encoding.UTF8);
            #endregion
            MessageBox.Show("保存成功");
            this.DialogResult = DialogResult.OK;
            this.Close();

        }

        private void Form2_Load(object sender, EventArgs e)
        {
            textBox1.Text = "默认分组";
        }
    }
}
